package com.jstyle.jclifexd.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.GroundOverlayOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.HistoryHeartRangeAdapter;
import com.jstyle.jclifexd.adapter.PaceAdapter;
import com.jstyle.jclifexd.adapter.TrackRecordDetailBaiDUAdapter;
import com.jstyle.jclifexd.daoManager.GpsDataDaoManager;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.GpsData;
import com.jstyle.jclifexd.model.HeartData;
import com.jstyle.jclifexd.model.PaceData;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.StepDetailData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.CoordinateUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.GlobalConst;
import com.jstyle.jclifexd.utils.HealthDataUtils;
import com.jstyle.jclifexd.utils.MapUtil;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.utils.WeakDataHolder;
import com.jstyle.jclifexd.view.ShareGpsView;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;


public class ExerciseHistoryActivity extends BaseActivity implements AMap.OnMapLoadedListener {

    @BindView(R.id.mapRecordDetail)
    MapView mapRecordDetail;
    @BindView(R.id.bt_trackhistory_mode)
    Button btTrackhistoryMode;
    @BindView(R.id.bt_trackhistory_diatance)
    Button btTrackhistoryDiatance;
    @BindView(R.id.recyclerView_track_detail)
    RecyclerView recyclerViewTrackDetail;
    @BindView(R.id.ColumnChartView_stephz)
    ColumnChartView ColumnChartView_stephz;
    @BindView(R.id.LineChartView_heart)
    LineChartView LineChartViewHeart;

    @BindArray(R.array.track_historydetail_array)
    String[] detailArray;
    @BindView(R.id.imageView6)
    ImageView imageView6;

    @BindView(R.id.imageView7)
    ImageView imageView7;
    @BindView(R.id.bt_trackhistory_stephz)
    Button btTrackhistoryStephz;
    @BindView(R.id.bt_trackhistory_avghz)
    Button btTrackhistoryAvghz;
    @BindView(R.id.bt_speed)
    Button btSpeed;
    @BindView(R.id.bt_heart)
    Button btHeart;

    @BindView(R.id.bt_heart_range)
    Button btHeartRange;
    @BindView(R.id.bt_heart_report)
    Button btHeartReport;

    @BindView(R.id.bt_trackhistory_space)
    Button btTrackHistorySpace;
    @BindView(R.id.bt_pace_low)
    TextView btPaceLow;
    @BindView(R.id.bt_space_fast)
    TextView btSpaceFast;
    @BindView(R.id.iv_color)
    ImageView ivColor;
    @BindView(R.id.tv_pace_label)
    TextView tvPaceLabel;
    @BindView(R.id.RecyclerView_pace)
    RecyclerView RecyclerViewPace;
    @BindView(R.id.RecyclerView_heartRange)
    RecyclerView RecyclerViewHeartRange;
    @BindView(R.id.bt_trackhistory_avgHeart)
    Button btTrackhistoryAvgHeart;
    @BindView(R.id.button_title)
    Button buttonTitle;
    @BindArray(R.array.mode_name)
    String[] modeName;

    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.bt_no_heartdata)
    Button btNoHeartdata;
    @BindView(R.id.ScrollView)
    NestedScrollView ScrollView;
    @BindView(R.id.view_hidden)
    View viewHidden;
    @BindView(R.id.tv_heart_level0)
    TextView tvHeartLevel0;
    @BindView(R.id.tv_heart_level1)
    TextView tvHeartLevel1;
    @BindView(R.id.tv_heart_level2)
    TextView tvHeartLevel2;
    @BindView(R.id.tv_heart_level3)
    TextView tvHeartLevel3;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;

    @BindView(R.id.iv_report_hr_level)
    ImageView ivReportHrLevel;
    @BindView(R.id.ConstraintLayout)
    android.support.constraint.ConstraintLayout ConstraintLayout;
    @BindView(R.id.view_divider)
    View viewDivider;
    @BindView(R.id.iv_hr_levelHr_general)
    ImageView ivHrLevelHrGeneral;
    @BindView(R.id.iv_hr_levelHr_good)
    ImageView ivHrLevelHrGood;
    @BindView(R.id.iv_hr_levelHr_excellent)
    ImageView ivHrLevelHrExcellent;
    @BindView(R.id.iv_hr_levelHr_tooHigh)
    ImageView ivHrLevelHrTooHigh;
    private PathRecord pathRecord;
    @BindString(R.string.heart_tips_0)
    String heartTips0;
    @BindString(R.string.heart_tips_1)
    String heartTips1;
    @BindString(R.string.heart_tips_2)
    String heartTips2;
    @BindString(R.string.heart_tips_3)
    String heartTips3;
    @BindArray(R.array.color_heartReport_array)
    int[] heartReportColor;
    Boolean isshoewStep = false;
    Boolean isshoewHeart = false;
    Boolean isshoewqujian = false;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    setupRecord();
                    break;
                default:
                    break;
            }
        }
    };
    private List<LatLng> mOriginLatLngList = new ArrayList<>();
    private AMap mAMap;
    private Polyline mOriginPolyline;
    private Marker mOriginStartMarker;
    private Marker mOriginEndMarker;
    private TrackRecordDetailBaiDUAdapter trackHistoryDetailAdapter;
    private int avgHeart;
    //    private AMapLocationClient mLocationClient;
//    private baidumapl mLocationOption;
    private ArrayList<Integer> stepList;
    private ArrayList<Integer> heartList;
    private String time;
    private String endTime;
    private int startCount;
    private int endCount;
    public static final String pathRecordDate = "DATE";
    private String mPathDate;
    private String lowPaceString;
    private String fastPaceString;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise_record_detail);
        ButterKnife.bind(this);
        mPathDate = getIntent().getStringExtra(pathRecordDate);
        pathRecord = PathRecordDaoManager.getPathRecord(mPathDate);
        if (isEnableMap(pathRecord.getExerciseMode())) mapRecordDetail.onCreate(savedInstanceState);
        init();
    }

























    private void init() {
        ScreenUtils.setTitleTypeface(buttonTitle);
        tvPaceLabel.setText(ResolveData.getDetailDistanceLabel(this));
        if (pathRecord == null) return;
        if (mAMap == null && isEnableMap(pathRecord.getExerciseMode())) {
            mAMap = mapRecordDetail.getMap();
            UiSettings uiSettings = mAMap.getUiSettings();
            uiSettings.setScrollGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(false);
//            uiSettings.setZoomControlsEnabled(false);
            Locale locale = getResources().getConfiguration().locale;
            String language = locale.getLanguage();
            mAMap.setMapLanguage(language);
            mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    if (Utils.isFastClick()) {
                        return;
                    }
                    Intent intent = new Intent(ExerciseHistoryActivity.this, TrackHistoryActivity.class);
                    WeakDataHolder.getInstance().setData(mOriginLatLngList);
                    startActivity(intent);
                }


            });
            mAMap.setOnMapLoadedListener(this);
        }
        btTrackhistoryMode.setText(modeName[pathRecord.getExerciseMode() > 10 ? 10 : pathRecord.getExerciseMode()]);
        initData();
    }

    private boolean isShowView(int mode) {
        boolean show = false;
        if (mode == ExerciseMode.Mode_RUN) {

        } else if (mode == ExerciseMode.Mode_CLIMB) {
            tvPaceLabel.setVisibility(View.GONE);
            btPaceLow.setVisibility(View.GONE);
            btSpaceFast.setVisibility(View.GONE);
            RecyclerViewPace.setVisibility(View.GONE);
            ivColor.setVisibility(View.GONE);
            btSpeed.setVisibility(View.GONE);
            btTrackHistorySpace.setVisibility(View.GONE);
        } else {
            ivColor.setVisibility(View.GONE);
            ColumnChartView_stephz.setVisibility(View.GONE);
            btTrackhistoryAvghz.setVisibility(View.GONE);
            btTrackhistoryStephz.setVisibility(View.GONE);
            tvPaceLabel.setVisibility(View.GONE);
            btPaceLow.setVisibility(View.GONE);
            btSpaceFast.setVisibility(View.GONE);
            RecyclerViewPace.setVisibility(View.GONE);
            btSpeed.setVisibility(View.GONE);
            btTrackHistorySpace.setVisibility(View.GONE);
            btTrackhistoryDiatance.setVisibility(View.GONE);
        }
        if (mode == ExerciseMode.Mode_CYCLING) btTrackhistoryDiatance.setVisibility(View.VISIBLE);
        return show;
    }

    private boolean isEnableMap(int mode) {
        boolean isEnable = false;
        if (mode == ExerciseMode.Mode_CYCLING || mode == ExerciseMode.Mode_RUN || mode == ExerciseMode.Mode_CLIMB)
            isEnable = true;
        return isEnable;
    }

    List<PaceData> paceList = new ArrayList<>();

    private void initData() {
        final int mode = pathRecord.getExerciseMode();
        boolean show = isShowView(mode);
        time = pathRecord.getMDate();
        buttonTitle.setText(DateUtil.getShowDayTrack(ExerciseHistoryActivity.this, time));

        String duration = pathRecord.getMDuration();
        long startL = DateUtil.getGpsDateLong(time);
        long endL = startL + Integer.valueOf(duration) * 1000;
        endTime = DateUtil.getFormatTimeString(endL);
        Log.i(TAG, "initData: " + endTime);
        startCount = DateUtil.get1MIndex(time, time.split(" ")[0] + " 00:00:00");
        endCount = DateUtil.get1MIndex(endTime, time.split(" ")[0] + " 00:00:00");

        initStepData();
        initHeartData();
        setRecyclerViewData();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                long t = System.currentTimeMillis();
                List<GpsData> gpsDataList = GpsDataDaoManager.getPathRecord(time, endTime);
                initGpsData(time, gpsDataList);
                Log.i(TAG, "subscribe: " + (System.currentTimeMillis() - t));
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                setPaceData();
                if (isEnableMap(mode)) {
                    if (mOriginLatLngList.size() == 0) {
                        mapRecordDetail.setVisibility(View.GONE);
                        viewHidden.setVisibility(View.VISIBLE);
                    } else {
                        isFinish = true;
                        Log.i(TAG, "onComplete: " + isMapLoaded);
                        Message msg = handler.obtainMessage();
                        msg.what = AMAP_LOADED;
                        handler.sendMessage(msg);
                    }
                } else {
                    mapRecordDetail.setVisibility(View.GONE);
                    viewHidden.setVisibility(View.VISIBLE);
                }


            }
        });


        ScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int i, int i1, int i2, int i3) {
                Rect scrollBounds = new Rect();
                ColumnChartView_stephz.getHitRect(scrollBounds);
                LineChartViewHeart.getHitRect(scrollBounds);
                RecyclerViewHeartRange.getHitRect(scrollBounds);
                if (!isshoewStep && ColumnChartView_stephz.getLocalVisibleRect(scrollBounds)) {
                    isshoewStep = true;
                    ChartDataUtil.settingXAnimator(ColumnChartView_stephz, 0);
                }
                if (!isshoewHeart && LineChartViewHeart.getLocalVisibleRect(scrollBounds)) {
                    isshoewHeart = true;
                    ChartDataUtil.settingXAnimator(LineChartViewHeart, 1);
                }

                if (!isshoewqujian && RecyclerViewHeartRange.getLocalVisibleRect(scrollBounds)) {
                    isshoewqujian = true;
                    initHeartRange(heartRanges);
                }

            }
        });
    }

    private void initHeartData() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryGpsData(time, endTime);
                heartList = new ArrayList<>();
                for (HeartData hr : heartDataList) {
                    String date = hr.getTime();
                    int heartValue = hr.getHeart();
                    int hrCount = DateUtil.get1MIndex(date, time.split(" ")[0] + " 00:00:00");
                    if (hrCount < startCount) continue;
                    if (hrCount >= endCount) break;
                    heartList.add(heartValue);
                }

                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                initHeartChartView(heartList);
                String avgHeartString = getString(R.string.avg) + String.valueOf(avgHeart) + " " + getResources().getString(R.string.hr_laber);
                btTrackhistoryAvgHeart.setText(getPaceSpannable(avgHeartString, String.valueOf(avgHeart)));
                trackHistoryDetailAdapter.setHeart(avgHeart);
                Log.i(TAG, "onComplete: heart");
            }
        });

    }

    private void initStepData() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                stepList = new ArrayList<>();
                List<StepDetailData> stepDetailDataList = StepDetailDataDaoManager.queryData(time.split(" ")[0] + " 00:00:00", endTime.split(" ")[0] + " 23:59:00");
                int stepLength = endCount > 1440 ? endCount : 1440;
                int[] stepArray = new int[stepLength];

                out:
                for (StepDetailData stepDetailData : stepDetailDataList) {
                    String date = stepDetailData.getDate();
                    String steps = stepDetailData.getMinterStep();
                    String[] stepString = steps.split(" ");//10分钟的步数
                    int stepCount = DateUtil.get1MIndex(date, time.split(" ")[0] + " 00:00:00");
                    in:
                    for (int i = 0; i < stepString.length; i++) {
                        int endStepCount = stepCount + i;
                        // Log.i(TAG, "subscribe: step "+endStepCount+" "+Integer.valueOf(stepString[i]));
                        if (endStepCount < startCount) continue in;
                        if (endStepCount >= endCount) continue out;
                        stepArray[endStepCount] = Integer.valueOf(stepString[i]);

                    }
                }
                for (int i = startCount; i < endCount; i++) {
                    stepList.add(stepArray[i]);
                }
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                initStepChartView(stepList);
            }
        });

    }

    boolean isDevice;

    private void initGpsData(String time, List<GpsData> gpsDataList) {
        float maxDistance = Float.valueOf(pathRecord.getMDistance());
        int maxPaceSize = (int) (maxDistance / 1);
        float lastDistance = maxDistance % 1;
        long totalTime = Integer.valueOf(pathRecord.getMDuration());
        LatLng lastLng = null;
        float distance = 0;
        long distanceTime = 0;
        int paceSize = 0;
        boolean paceFinish = false;
        long lastL = DateUtil.getGpsDateLong(time);
        out:
        for (GpsData gpsData : gpsDataList) {
            String date = gpsData.getDate();
            // Log.i(TAG, "initGpsData: " + date);
            long gpsStartL = DateUtil.getGpsDateLong(date);
            String pathLineString = gpsData.getPathLineString();
            if (!TextUtils.isEmpty(pathLineString)) {//手机存储gps数据
                //  Log.i(TAG, "initGpsData: path");
                if (isDevice) continue out;
                List<AMapLocation> aMapLocationList = MapUtil.parseLocations(pathLineString);
                mOriginLatLngList = MapUtil.parseLatLngList(aMapLocationList);
            } else {//手环数据
                isDevice = true;
                if (distance == 0) {
                    distanceTime = DateUtil.getGpsDateLong(date);
                }
                String[] LatitudeStringArray = gpsData.getLatitudeString().split(",");
                String[] LongitudeStringArray = gpsData.getLongitudeString().split(",");
                in:
                for (int i = 0; i < LatitudeStringArray.length; i++) {
                    // Log.i(TAG, "initGpsData: "+LatitudeStringArray[i]+" "+LongitudeStringArray[i]);
                    LatLng latLng = CoordinateUtil.transformFromWGSToGCJ(
                            new LatLng(Double.valueOf(LatitudeStringArray[i]), Double.valueOf(LongitudeStringArray[i])));
                    if (mOriginLatLngList.size() != 0) {
                        double betweenDis = AMapUtils.calculateLineDistance(lastLng,
                                latLng);
                        //  Log.i(TAG, "initGpsData: dis " + betweenDis);
                        long duration = (gpsStartL + i * 1000 - lastL) / 1000;
                        //    Log.i(TAG, "initGpsData: duration " + duration);
                        if (betweenDis > 100 * duration) continue in;
                    }
                    mOriginLatLngList.add(latLng);
                    if (lastLng != null) {
                        //   Log.i(TAG, "initGpsData: "+latLng.latitude+" "+latLng.longitude+" "+lastLng.latitude+" "+lastLng.longitude);
                        if (distance == 0 || paceList.size() > paceSize) {
                            distanceTime = DateUtil.getGpsDateLong(date);
                            paceSize = paceList.size();
                        }
                        double betweenDis = AMapUtils.calculateLineDistance(lastLng,
                                latLng);
                        distance = (float) (distance + betweenDis);
                        if (paceList.size() == maxPaceSize) {
                            if (distance >= lastDistance * 1000) {
                                long durtaion = 0;
                                for (PaceData paceData : paceList) {
                                    durtaion += paceData.getPace();
                                }
                                PaceData paceData = new PaceData();
                                paceData.setPace((totalTime - durtaion) / distance);
                                paceData.setTime((totalTime - durtaion));
                                paceData.setDistanceFinish(false);
                                paceList.add(paceData);
                                paceFinish = true;
                            }
                        }
                        if (distance >= getPaceDistance() && !paceFinish) {
                            long durtaion = DateUtil.getGpsDateLong(date) - distanceTime;
                            PaceData paceData = new PaceData();
                            paceData.setPace(durtaion / distance);
                            paceData.setDistanceFinish(true);
                            paceList.add(paceData);
                            distance = distance - getPaceDistance();
                            //       Log.i(TAG, "initGpsData: distance " + distance);
                        }
                    }
                    lastLng = latLng;
                    lastL = gpsStartL + i * 1000;
                }
                if (!paceFinish && gpsDataList.indexOf(gpsData) == gpsDataList.size() - 1 && paceList.size() == paceSize) {
                    long durtaion = 0;
                    for (PaceData paceData : paceList) {
                        durtaion += paceData.getPace();
                    }
                    PaceData paceData = new PaceData();
                    paceData.setPace((totalTime - durtaion) / distance);
                    paceData.setTime((totalTime - durtaion));
                    paceData.setDistanceFinish(false);
                    paceList.add(paceData);
                }
            }

        }

    }

    private float getPaceDistance() {
        boolean enable_DistanceUnit = SharedPreferenceUtils.getBoolean(GlobalConst.KEY_DistanceUnit, false);
        return enable_DistanceUnit ? 1000 * 1.6093f : 1000;
    }

    boolean isDrawMap;

    private void setupRecord() {
        if (mAMap == null) return;
        Log.i(TAG, "setupRecord: " + mOriginLatLngList.size());
        List<LatLng> pathoptimizeList = mOriginLatLngList;
        if (pathRecord != null && isFinish && isMapLoaded) {
            if (pathoptimizeList.size() == 0 || isDrawMap) return;
            isDrawMap = true;
            LatLng startLatLng = pathoptimizeList.get(0);
            LatLng endLatLng = pathoptimizeList.get(pathoptimizeList.size() - 1);
            addOriginTrace(startLatLng, endLatLng, pathoptimizeList);
//            if (!NetWorkUtil.isNetworkConnected(this))
//                showToast(getString(R.string.Network_not_availa_map));

        } else {
        }

    }
    boolean isFinish;
    boolean isMapLoaded;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mOriginLatLngList != null && mOriginLatLngList.size() != 0)
            mapRecordDetail.onDestroy();
        isshoewStep = false;
        isshoewHeart = false;
        isshoewqujian = false;
    }


    private void addOriginTrace(LatLng startPoint, LatLng endPoint,
                                List<LatLng> originList) {
        Log.i(TAG, "addOriginTrace: ");
        mOriginPolyline = mAMap.addPolyline(new PolylineOptions().color(
                Color.GREEN).width(ScreenUtils.dip2px(this, 6)).addAll(originList).zIndex(2));
        mOriginStartMarker = mAMap.addMarker(new MarkerOptions().position(
                startPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
        mOriginEndMarker = mAMap.addMarker(new MarkerOptions().position(
                endPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));
        int height = mapRecordDetail.getHeight();
        int width = mapRecordDetail.getWidth();
        Log.i(TAG, "addOriginTrace: " + height);
        try {
            mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),
                    height / 3));
            mAMap.addGroundOverlay(new GroundOverlayOptions()
                    .position(endPoint, 2 * 1000 * 1000, 2 * 1000 * 1000)
                    .image(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(this.getResources(), R.drawable.ic_marker_bg))).zIndex(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    int[] heartRanges = new int[5];

    private void initHeartChartView(List<Integer> heartList) {
        float maxHeartRate = 0;
        List<PointValue> pointValues = new ArrayList<>();
        float totalHeartRate = 0;
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        int MHR = 220 - age;
        heartRanges = new int[5];
        int count = 0;
        float maxHr = 0;
        float minHr = 300;
        for (int i = 0; i < heartList.size(); i++) {
            float heartRate = heartList.get(i);
            maxHr = Math.max(maxHr, heartRate);
            minHr = Math.min(minHr, heartRate);
            int level = HealthDataUtils.getHeartRange(heartRate);
            if (level != -1) heartRanges[level]++;
            if (heartRate != 0) count++;
            totalHeartRate += heartRate;
            pointValues.add(new PointValue(i, heartRate));
            maxHeartRate = Math.max(maxHeartRate, heartRate);
        }
        getHeartReport(heartRanges, count);
        avgHeart = count == 0 ? 0 : (int) Math.rint((totalHeartRate / count));
        float top = 0;
        if (maxHr % 10 == 0) {
            top = maxHr;
        } else {
            top = (((int) maxHr / 10) + 1) * 10;
        }
        if (stepList.size() > 5) {
            ChartDataUtil.initDataChartView(LineChartViewHeart,
                    -0.5f, top + 10, heartList.size() - 0.3f, 40);
        } else {
            ChartDataUtil.initDataChartView(LineChartViewHeart,
                    -0.5f, top + 10, 20 - heartList.size(), 40);
        }
        LineChartViewHeart.setLineChartData(ChartDataUtil.getTrackHistoryHeartChart(this, pointValues));

    }

    private void setHeartRange(int[] heartRanges) {
        float total = 0;
        for (int i = 0; i < 6; i++) {
            total += heartRanges[i];
        }

    }

    private int getHeartRange(float heartRate, int MHR) {
        int range = 0;
        if (heartRate >= 0.5f * MHR && heartRate <= 0.6f * MHR) {//热身
            range = 0;
        } else if (heartRate >= 0.6f * MHR && heartRate < 0.7f * MHR) {//燃脂
            range = 1;
        } else if (heartRate >= 0.7f * MHR && heartRate < 0.8f * MHR) {//有氧
            range = 2;
        } else if (heartRate >= 0.8f * MHR && heartRate < 0.9f * MHR) {//肌力
            range = 3;
        } else if (heartRate >= 0.9f * MHR) {//无氧
            range = 4;
        }
        return range;
    }

    private float getDistance(List<LatLng> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            LatLng firstLatLng = list.get(i);
            LatLng secondLatLng = list.get(i + 1);
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }

        return distance;
    }
//    public  ArrayList<AMapLocation> parseLocations(String latLonStr) {
//        ArrayList<AMapLocation> locations = new ArrayList<AMapLocation>();
//        String[] latLonStrs = latLonStr.split(";");
//        for (int i = 0; i < latLonStrs.length; i++) {
//            AMapLocation location = parseLocation(latLonStrs[i]);
//            if (location != null) {
//                locations.add(location);
//            }
//        }
//        return locations;
//    }
//    public  AMapLocation parseLocation(String latLonStr) {
//        if (latLonStr == null || latLonStr.equals("") || latLonStr.equals("[]")) {
//            return null;
//        }
//        String[] loc = latLonStr.split(",");
//        AMapLocation location = null;
//        if (loc.length == 6) {
//            location = new AMapLocation(loc[2]);
//            location.setProvider(loc[2]);
//            location.setLatitude(Double.parseDouble(loc[0]));
//            location.setLongitude(Double.parseDouble(loc[1]));
//            location.setTime(Long.parseLong(loc[3]));
//            location.setSpeed(Float.parseFloat(loc[4]));
//            location.setBearing(Float.parseFloat(loc[5]));
//        }else if(loc.length == 2){
//            location = new AMapLocation("gps");
//            location.setLatitude(Double.parseDouble(loc[0]));
//            location.setLongitude(Double.parseDouble(loc[1]));
//        }
//
//        return location;
//    }

//    public  List<LatLng> parseLatLngList(List<AMapLocation> list) {
//        List<LatLng> traceList = new ArrayList<LatLng>();
//        if (list == null) {
//            return traceList;
//        }
//        for (int i = 0; i < list.size(); i++) {
//            AMapLocation loc = list.get(i);
//            double lat = loc.getLatitude();
//            double lng = loc.getLongitude();
//            LatLng latlng = new LatLng(lat, lng);
//            traceList.add(latlng);
//        }
//        return traceList;
//    }

    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = new LatLngBounds.Builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }

        return b.build();

    }

    /**
     * 配速
     */
    private void setPaceData() {

        float minPace = 10000;
        float maxPace = 0;
        for (PaceData paceData : paceList) {
            if (paceData.isDistanceFinish()) {
                minPace = Math.min(minPace, paceData.getPace());
                maxPace = Math.max(maxPace, paceData.getPace());
            }

        }
        lowPaceString = getString(R.string.Slowst) + ResolveData.getShowPace(this, DateUtil.getPaceTime((int) maxPace));
        fastPaceString = getString(R.string.Fast) + ResolveData.getShowPace(this, DateUtil.getPaceTime(minPace == 10000 ? 0 : (int) minPace));
        btPaceLow.setText(lowPaceString);
        btSpaceFast.setText(fastPaceString);
        PaceAdapter paceAdapter = new PaceAdapter(paceList, maxPace, minPace);
        RecyclerViewPace.setAdapter(paceAdapter);
        LinearLayoutManager linearLayoutManagerPace = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        linearLayoutManagerPace.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewPace.setLayoutManager(linearLayoutManagerPace);

    }

    private void setRecyclerViewData() {
        trackHistoryDetailAdapter = new TrackRecordDetailBaiDUAdapter(this, pathRecord, avgHeart);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        recyclerViewTrackDetail.setLayoutManager(flexboxLayoutManager);
        recyclerViewTrackDetail.setAdapter(trackHistoryDetailAdapter);
        int time = Integer.valueOf(pathRecord.getMDuration());//时间
        float step = TextUtils.isEmpty(pathRecord.getMStep()) ? 0 : Float.valueOf(pathRecord.getMStep());//步数
        int stepM = (int) step * 60 / time;//平均步频
        float distance = Float.valueOf(pathRecord.getMDistance());//距离
        String showDistance = null;
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        showDistance = ResolveData.getShowDistance(String.valueOf(distance));
        String showPace = ResolveData.getShowPace(this, pathRecord.getMAveragespeed());
        String distanceString = showDistance + ResolveData.getDistanceLabel(this);
        String avgPaceString = ResolveData.getDetailPaceLabel(this, showPace);
        btTrackhistoryDiatance.setText(getPaceSpannable(distanceString, showDistance));
        btTrackHistorySpace.setText(getPaceSpannable(avgPaceString, showPace));

    }

    private static final String TAG = "ExerciseHistoryActivity";

    private void initHeartRange(int[] heartRanges) {
        int total = 0;
        for (int i = 0; i < 5; i++) {
            total += heartRanges[i];
        }
        HistoryHeartRangeAdapter historyHeartRangeAdapter = new HistoryHeartRangeAdapter(this, heartRanges, total);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHeartRange.setAdapter(historyHeartRangeAdapter);
        RecyclerViewHeartRange.setLayoutManager(linearLayoutManager);
    }

    private void getHeartReport(int[] heartRanges, int total) {
        float range0 = heartRanges[0];
        float range1 = heartRanges[1];
        float range2 = heartRanges[2];
        float range3 = heartRanges[3];
        float range4 = heartRanges[4];
        String tips = "";
        String level = "";
        int pieValue = -1;
        if (range4 > 5 || (range3 + range4) > 20 || range3 > 20) {//过高
            tips = heartTips3;
            ivHrLevelHrTooHigh.setVisibility(View.VISIBLE);
        } else if ((range2 >= 20 && range2 <= 30) || (range3 >= 10 && range3 <= 20) || (range4 > 0 && range4 <= 5 && range3 + range4 > 2) || range2 + range3 >= 20) {//优秀
            tips = heartTips2;
            ivHrLevelHrExcellent.setVisibility(View.VISIBLE);
        } else if ((range0 + range1 + range2 + range3 > 30 && range1 > 20) || (range3 > 0 && range3 < 10 && range2 + range3 > 2) || (range2 > 5 && range2 < 20) || range1 + range2 + range3 > 30) {//良好
            tips = heartTips1;
            ivHrLevelHrGood.setVisibility(View.VISIBLE);
        } else {//弱
            tips = heartTips0;
            if (total != 0) ivHrLevelHrGeneral.setVisibility(View.VISIBLE);
        }
        tvResult.setText(tips);
        if (total == 0) level = getString(R.string.No_data);


    }

    private void initStepChartView(List<Integer> stepList) {
        int time = Integer.valueOf(pathRecord.getMDuration());
        float step = TextUtils.isEmpty(pathRecord.getMStep()) ? 0 : Float.valueOf(pathRecord.getMStep());//之前版本步数设为浮点了
        int stepM = (int) Math.rint(Double.valueOf(step) * 60 / time);
        String paceStringAvg = getString(R.string.avg) + stepM + " " + getString(R.string.Stride_label);
        btTrackhistoryAvghz.setText(getPaceSpannable(paceStringAvg, stepM + ""));
        if (stepM == 0) return;
        float max = 0;
        for (Integer data : stepList) {
            max = Math.max(data, max);
        }

        if (stepList.size() > 12) {
            ChartDataUtil.initDataChartView(ColumnChartView_stephz, -0.5f, max == 0 ? 2 : max * 1.2f, time / 60 + 0.5f, 0);
        } else {
            ChartDataUtil.initDataChartView(ColumnChartView_stephz, -0.5f, max == 0 ? 2 : max * 1.2f, 12f, 0);

        }


        ColumnChartView_stephz.setColumnChartData(ChartDataUtil.getTrackStepColumnChart(this, time, stepList));

        if (mAMap == null && isEnableMap(pathRecord.getExerciseMode())) {
            if (!isshoewStep) {
                isshoewStep = true;
                ChartDataUtil.settingXAnimator(ColumnChartView_stephz, 0);
            }
        }
    }

    private float max = 0;

    private List<Float> string2List(String data) {
        List<Float> list = new ArrayList<>();
        if (TextUtils.isEmpty(data)) return list;
        String[] datas = data.split(",");
        for (String value : datas) {
            list.add(Float.valueOf(value));
        }

        return list;
    }

    @OnClick({R.id.imageView6, R.id.imageView7})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.imageView6:
                finish();
                break;
            case R.id.imageView7:
                startShoot();

                break;
        }
    }

    private void startShoot() {
        WeakDataHolder.getInstance().setData(mOriginLatLngList);
        if (mOriginLatLngList != null && mOriginLatLngList.size() != 0) {
            ShareGpsView shareGpsView = new ShareGpsView(this, time);
            final Bitmap bitmapGps = shareGpsView.getBitmap();
            if (null != mAMap)
                mAMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
                    @Override
                    public void onMapScreenShot(Bitmap bitmap) {

                        ScreenUtils.shareMapFile(ExerciseHistoryActivity.this, bitmap, bitmapGps, ScrollView, mPathDate, fastPaceString, lowPaceString);

                    }

                    @Override
                    public void onMapScreenShot(Bitmap bitmap, int i) {

                    }
                });

        } else {
            ScreenUtils.shareFile(ExerciseHistoryActivity.this, ScrollView, mPathDate);
        }


    }


    private Spannable getDistanceSpannable(String text, String startText) {
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 10);
        return kcalSpannable;
    }

    private Spannable getPaceSpannable(String text, String startText) {
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 20);
        return kcalSpannable;
    }

    private void setSizeSpannable(Spannable word, int start, int end, int textSize) {
        word.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    private final static int AMAP_LOADED = 2;

    @Override
    public void onMapLoaded() {
        Log.i(TAG, "onMapLoaded: " + isFinish);
        isMapLoaded = true;
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

    @OnClick(R.id.bt_heart_range)
    public void onViewClicked() {
        startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_ActivityHeart);

    }
    //登录


}
